//
//  AccountManager.swift
//  Xiaozihui
//
//  Created by 校企荟 on 2017/10/9.
//  Copyright © 2017年 校企荟. All rights reserved.
//

import UIKit
import YYModel

//登录成功通知
let kLoginSuccessNotificationName = "kLoginSuccessNotificationName"

//登出通知
let kLogOutSuccessNotificationName = "kLogOutSuccessNotificationName"


enum AccountType: Int{
    case USER = 0
    case SERVICEMAN
}


/*
 Data =     {
 id = 1;
 img = "";
 license = 45121324654;
 name = "\U59dc\U5947";
 password = 123456;
 service = "\U7535\U8111"; //电脑
 style = 1;
 supplier = "\U6821\U4f01\U835f"; //维修单位
 tel = 18525426856;//账号 手机号
 tie = "\U5143\U6c5f\U8def\U6c47\U529b\U5f97\U5546\U52a1\U56ed\U533a"; //地址
 token = 9401db8eb1b9d62b537334d251c87c02;
 };
 code = 200;
 msg = "\U7528\U6237\U767b\U5f55\U6210\U529f";
 */


let documentPath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last! + "/account.plist"

class AccountManager: NSObject {
    static let sharedManager:AccountManager = AccountManager()
    var user : User?
//
//    var accountType: AccountType {
//        get {
//            return AccountType(rawValue: UserDefaults.standard.integer(forKey: "accountType")) ?? AccountType(rawValue: 0)!
//        }
//        set {
//            UserDefaults.standard.set(newValue, forKey: "username")
//        }
//    }
//
//    var name: String {
//        get {
//            return UserDefaults.standard.string(forKey: "name") ?? ""
//        }
//        set {
//            UserDefaults.standard.set(newValue, forKey: "name")
//        }
//    }
//
//    var username: String {
//        get {
//            return UserDefaults.standard.string(forKey: "username") ?? ""
//        }
//        set {
//            UserDefaults.standard.set(newValue, forKey: "username")
//        }
//    }
//
//    var member_id: String {
//        get {
//            return UserDefaults.standard.string(forKey: "member_id") ?? ""
//        }
//        set {
//            UserDefaults.standard.set(newValue, forKey: "member_id")
//        }
//    }
//
//    var token: String {
//        get {
//            return UserDefaults.standard.string(forKey: "token") ?? ""
//        }
//        set {
//            UserDefaults.standard.set(newValue, forKey: "token")
//        }
//    }
//
//    var icon: String {
//        get {
//            return UserDefaults.standard.string(forKey: "icon") ?? ""
//        }
//        set {
//            UserDefaults.standard.set(newValue, forKey: "icon")
//        }
//    }
//
//    var company: String {
//        get {
//            return UserDefaults.standard.string(forKey: "company") ?? ""
//        }
//        set {
//            UserDefaults.standard.set(newValue, forKey: "company")
//        }
//    }
//
//    var expirationTime: NSNumber? {
//        get {
//            return UserDefaults.standard.object(forKey: "expirationTime") as? NSNumber
//        }
//        set {
//            UserDefaults.standard.set(newValue, forKey: "expirationTime")
//        }
//    }
    override init() {
        super.init()
        
//        guard let expirationTimeDoubleValue = expirationTime?.doubleValue else {
//            loginOut()
//            return
//        }
//
//        if expirationTimeDoubleValue < NSDate().timeIntervalSince1970 {
//            loginOut()
//        }
        
        
        
        
    }
    
    

    
    //检查是否登录
    func checkIsLogin() -> Bool {
        if loadUser()?.token == nil || loadUser()?.token == ""   {
            loginOut()
            UIApplication.shared.keyWindow?.rootViewController?.present(LoginVC(), animated: false, completion: nil)
            return false
        } else {
            return true
        }
    }
    
    //登录
    func login(username:String,password:String,finished:@escaping ((_ isSuccess:Bool)->())){
        
        NetworkManager.sharedManager.request(method: .POST, URLString: PostLoginUrl, parameters: ["tel":username,"password":password]) { (response, error) in
            
            if error != nil {
                finished(false)
                return
            }
            
            guard let dict = response as? [String : Any?] else {
                
                finished(false)
                return
            }
            
            guard let data = dict["Data"] as? [String : Any?] else {
                finished(false)
                return
                
            }
            
          
            self.user = User(dic: data)


            self.saveUserAccount(user: self.user!)

            NotificationCenter.default.post(name: NSNotification.Name(rawValue: kLoginSuccessNotificationName), object: nil)
        }
    }
    
    //登出
    func loginOut() -> () {
    
        deleteUser()
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: kLogOutSuccessNotificationName), object: nil)
    }
    
    func deleteUser() {
       try? FileManager.default.removeItem(atPath: documentPath)
    }
    
    func saveUserAccount(user : User) {
        
        NSKeyedArchiver.archiveRootObject(user, toFile: documentPath)
        
    }
    
    func loadUser() -> User? {
        
        user = NSKeyedUnarchiver.unarchiveObject(withFile: documentPath) as? User
        
        return NSKeyedUnarchiver.unarchiveObject(withFile: documentPath) as? User
    }
    
    
}
